package dao;

import model.User;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/4/1 22:48
 */
public class UserDao {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    /**
     * 通过名称获取用户信息
     * @return
     */
    public User selectByName(String name){
        connection = DBUtils.getConnection();
        if (connection==null){
            return null;
        }
        User user = null;
        try{
            String sql = "select * from user where user_name = ? and delete_flag=0" ;
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                user = new User();
                user.setId(resultSet.getInt("id"))
                        .setUserName(resultSet.getString("user_name"))
                        .setPasswd(resultSet.getString("password"))
                        .setGithubUrl(resultSet.getString("github_url"))
                        .setDeleteFlag(resultSet.getInt("delete_flag"))
                        .setCreateTime(resultSet.getTimestamp("create_time"))
                        .setUpdateTime(resultSet.getTimestamp("update_time"));
            }
        }catch (SQLException e ){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return user;
    }
    /**
     * 通过ID来获取用户信息
     * @return
     */
    public User selectById(Integer id){
        connection = DBUtils.getConnection();
        if (connection==null){
            return null;
        }
        User user = null;
        try{
            String sql = "select * from user where id = ?" ;
            statement = connection.prepareStatement(sql);
            statement.setInt(1,id);
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                user = new User();
                user.setId(resultSet.getInt("id"))
                        .setUserName(resultSet.getString("user_name"))
                        .setPasswd(resultSet.getString("password"))
                        .setGithubUrl(resultSet.getString("github_url"))
                        .setDeleteFlag(resultSet.getInt("delete_flag"))
                        .setCreateTime(resultSet.getTimestamp("create_time"))
                        .setUpdateTime(resultSet.getTimestamp("update_time"));
            }
        }catch (SQLException e ){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return user;
    }
}
